package com.project.controller;

import com.alibaba.excel.EasyExcelFactory;
import com.project.entity.AssetType;
import com.project.entity.Staff;
import com.project.service.AssetTypeService;
import com.project.service.StaffService;
import com.project.util.SpinnerWriteHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Leo高洋
 * @create 2023-03-15 17:08
 */
@Controller
public class ExcelController {
    @Autowired
    private AssetTypeService assetTypeService;

    @Autowired
    private StaffService staffService;

    private final static Logger logger = LoggerFactory.getLogger(ExcelController.class);

    @GetMapping("/exportExcelTemplate")
    @ResponseBody
    public void exportExcelTemplate(HttpServletResponse response) throws IOException {
        logger.info("导出摸板文件");
        String fileName = "资产设备基本信息登记表.xlsx";
        List<AssetType> assetTypeList = assetTypeService.getAll();
        List<String> collect = assetTypeList.stream().map(AssetType::getName).collect(Collectors.toList());
        List<Staff> staffList = staffService.getList();
        List<String> collect2 = staffList.stream().map(Staff::getName).collect(Collectors.toList());
        // 响应类型,编码
        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=template.xlsx");
        EasyExcelFactory.write(response.getOutputStream())
                .withTemplate(this.getClass().getResourceAsStream("/excelTemplate/" + fileName))
                .registerWriteHandler(new SpinnerWriteHandler(collect, collect2))// 将下拉选框需要的值通过构造方法传进SpinnerWriteHandler
                .sheet()// 由于导出的是模板，这里不需要填充数据，如果需要填充数据，这里传真实的业务数据即可
                .doWrite(Collections.emptyList());
    }
}
